package com.sjy.mvvmdemo

import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.sjy.mvvmdemo.databinding.ActSecondBinding
import com.sjy.mvvmdemo.roomdb.SecondAdapter
import com.sjy.mvvmdemo.roomdb.SecondViewModel
import com.sjy.mvvmdemo.roomdb.db.UserDatabase
import com.sjy.mvvmdemo.roomdb.db.UserEntity
import com.sjy.mvvmdemo.roomdb.dbfactory.UserRepository
import com.sjy.mvvmdemo.roomdb.dbfactory.UserViewModelFactory

/**
 * 使用技术：viewModel(liveData)+databinding+Room
 * 演示recyclerView于room绑定
 */
class SecondActivity : AppCompatActivity() {

    //lateinit表示延迟初始化
    lateinit var binding: ActSecondBinding
    lateinit var mSecondViewModel: SecondViewModel
    lateinit var adapter: SecondAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //databinding绑定
        binding = ActSecondBinding.inflate(layoutInflater, null, false)
        setContentView(binding.root)

        initViewModel()
        initRecyclerView()

        initListener()
    }

    /**
     *  使用ViewModel操作数据
     */
    private fun initViewModel() {
        //绑定db
        val mUserDao = UserDatabase.getInstance(application).mUserDao
        val mUserRepository = UserRepository(mUserDao)
        val factory = UserViewModelFactory(mUserRepository)
        //vm和db绑定  最新写法 获取和xml交互的对象
        mSecondViewModel = ViewModelProvider(this, factory).get(SecondViewModel::class.java)
        //和xml布局绑定
        binding.mSecondViewModel = this.mSecondViewModel
        //绑定lifecycle
        binding.lifecycleOwner = this
    }

    //xml绑定RecyclerView
    private fun initRecyclerView() {
        adapter = SecondAdapter({ mItemSelect: UserEntity -> listItemClicked(mItemSelect) })
        binding.recyclerView.layoutManager = LinearLayoutManager(this)
        binding.recyclerView.adapter = adapter
        showLists()
    }

    /**
     * list选中后，赋值在输入框的位置
     */
    fun listItemClicked(mUser: UserEntity) {
        mSecondViewModel.showView(mUser);
    }

    private fun initListener() {
        //监听错误提示
        mSecondViewModel.msg.observe(this, Observer {
            it?.let {
                Toast.makeText(this, it, Toast.LENGTH_LONG).show()
            }
        })
    }

    private  fun showLists(){
        mSecondViewModel.userLists.observe(this, Observer {
            adapter.updateData(it)
        })
    }
}
